<!--
 * @Author: shenqi
 * @Date: 2021-09-08 10:08:28
 * @LastEditors: shenqi
 * @LastEditTime: 2021-09-14 09:15:34
 * @Description: file content
 * @FilePath: \xh-iot-web\src\components\JsonEditors\index.vue
-->
<template>
  <div class="json_editor">
    <div id="editor_holder"></div>
  </div>
</template>
<script>
//根据自己的相关文件位置找到对应路径
import "@/utils/jsoneditor.js";
// import "@/assets/css/jsonEditor/foundation.min.css";
// import "@/assets/css/jsonEditor/font-awesome.css";
export default {
  props: {
    jsonData: {
      type: Object,
      default: () => {},
    },
  },
  data() {
    return {
      form: {},
      schema: {
        title: "JSON文件",
        type: "object",
        properties: this.jsonData,
      },
      editor: null,
      dataFlag: null,
      count: 0,
    };
  },
  watch: {
    jsonData:{
      deep: true,
      handler: function (newV, oldV) {
        console.log("jsonDatanewV中：", newV);
        // console.log("jsonDataoldV中：", oldV);
        // this.upData(newV)
      },
    }
  },
  mounted() {
    window.addEventListener("onbeforeunload ", this.beforeunloadHandler());
    let that = this;
    let element = window.document.getElementById("editor_holder");
    let config = {
      schema: {},
      iconlib: "fontawesome3", //设置字体
      theme: "foundation5", //设置主题,可以是bootstrap或者jqueryUI等
      disable_properties: false, //如果设置为 true, 将隐藏编辑属性按钮.
      // required_by_default: true,
      //   disable_edit_json: true, //如果设置为 true, 将隐藏 Edit JSON 按钮.
      object_layout: "normal ", //属性为object时,属性默认normal,设置grid可以一排多个
      disable_collapse: false, //如果设置为 true, 对象和数组不再显示“折叠”按钮.
      custom_validators: [],
    };
    config["schema"] = this.schema;
    this.editor = new window.JSONEditor(element, config);
    let datas = that.editor.getValue();
    let dataTables = datas.Module_RS485.Slave.Binding_Table;
    this.dataFlag = dataTables;
    that.$emit("upDatas", datas);
    this.editor.on("change", function () {
      let data = that.editor.getValue();
      console.log(data, "现在的值");
      // console.log(that.editor, "现在的这个");
      that.$emit("upDatas", data);
      let dataTable = data.Module_RS485.Slave.Binding_Table;
      let beforeDataTable = JSON.parse(localStorage.getItem("beforeDataTable"));
      that.dataFlag = beforeDataTable ? beforeDataTable : that.dataFlag;
      let nowArr = dataTable.filter((items) => {
        return !that.dataFlag.some((item) => {
          return items.DeviceID === item.DeviceID;
        });
      });
      let tableIndex = [];
      dataTable.forEach((item, index) => {
        if (nowArr && nowArr[0] && nowArr[0].DeviceID == item.DeviceID) {
        }
        tableIndex.push(item.DeviceID);
      });
      if (tableIndex && tableIndex.length && nowArr.length) {
        let index = tableIndex.indexOf(nowArr[0].DeviceID);
        that.watchData(index);
      }
    });
    this.editor.off("change", function () {});
  },
  methods: {
    beforeunloadHandler() {
      localStorage.removeItem("beforeDataTable");
    },
    upData(data) {
      console.log(data,'改变')
      this.editor.setValue(data);
    },
    isRepeat(arr) {
      var hash = {};
      for (var i in arr) {
        if (hash[arr[i]]) return true;
        hash[arr[i]] = true;
      }
      return false;
    },
    watchData(index) {
      let that = this;
      this.editor.watch("root.Module_RS485.Slave.Binding_Table", function () {
        console.log("监听");
        that.editor.options.custom_validators.push(function (
          schema,
          value,
          path
        ) {
          var errors = [];
          if (
            path === `root.Module_RS485.Slave.Binding_Table.${index}.DeviceID`
          ) {
            let dataTable =
              that.editor.getValue().Module_RS485.Slave.Binding_Table;
            setTimeout(() => {
              localStorage.setItem(
                "beforeDataTable",
                JSON.stringify(dataTable)
              );
            }, 500);
            let dataArr =
              that.editor.getValue().Module_RS485.Slave.Binding_Table;
            let array = [];
            dataArr.forEach((item, index) => {
              array.push(item.DeviceID);
            });
            console.log(array);
            let flag = that.isRepeat(array);
            let message = "DeviceID不能有相同的值";
            let arrFlag = [];
            if (flag) {
              errors.push({
                path: path,
                property: "format",
                message: message,
              });
            } else {
              that.editor.validation_results.map((item) => {
                arrFlag.push(item.message);
              });
              if (arrFlag.indexOf(message) > -1) {
                that.editor.validation_results.splice(
                  arrFlag.indexOf(message),
                  1
                );
              }
              that.editor.options.custom_validators = [];
            }
          }
          that.unwatchTable();
          return errors;
        });
      });
      let result = this.editor.validation_results;
      let result1 = this.editor;
      console.log(result1);
      let obj = {};
      result = result.reduce(function (item, next) {
        obj[next.key] ? "" : (obj[next.key] = true && item.push(next));
        return item;
      }, []);
      this.editor.validation_results = result;
    },
    unwatchTable() {
      this.editor.unwatch(
        "root.Module_RS485.Slave.Binding_Table",
        this.function_reference()
      );
    },
    function_reference(v) {},
  },
  destroyed() {
    localStorage.removeItem("beforeDataTable");
  },
};
</script>
<style lang="scss" scoped>
#editor_holder {
  max-height: calc(100vh - 250px);
  min-height: 300px;
  overflow-y: scroll;
  width: 100%;
  .je-object__container {
    height: 100%;
  }
}
.json_editor {
  .editor-button {
    width: 100%;
    margin: auto;
  }
}
.forms {
  margin-top: 30px;
}
</style>